package com.xjh.mange.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjh.mange.common.constant.UserSessionName;
import com.xjh.mange.common.enums.DeleteStatusEnum;
import com.xjh.mange.model.User;
import com.xjh.mange.model.Web;
import com.xjh.mange.service.LogService;
import com.xjh.mange.service.WebService;
import com.xjh.mange.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @author 徐佳辉
 * @date 2020/12/22 16:36
 */
@Controller
@RequestMapping("/web")
@Slf4j
public class WebController {

    @Autowired
    private WebService webService;
    @Value("${web.url}")
    private String webPicUrl;
    @Autowired
    private LogService logService;


    /**
     * 添加或更新
     *
     * @param web
     * @return
     */
    @PostMapping("/insert")
    @ResponseBody
    public ResponseVO insert(@RequestBody Web web, HttpSession session) {
        User user = (User) session.getAttribute(UserSessionName.USER);
        if (user == null) {
            return ResponseVO.error("请登录");
        }
        log.info("web:[{}]", web);
        if (web.getId() != null) {
            web.setUpdateTime(new Date());
            boolean b = webService.updateById(web);

            return b ? ResponseVO.ok("更新成功") : ResponseVO.error("更新失败");
        } else {
            if (StringUtils.isBlank(web.getWebIcon())) {
                Random random = new Random();
                int r = random.nextInt(14) + 1;
                // 赋予项目里的图片14中随机一张
                web.setWebIcon("../imgs/" + r + ".png");
            }
            web.setDel(DeleteStatusEnum.NOT_DELETE.getCode());
            web.setUserName(user.getUserName());
            web.setCreateTime(new Date());
            log.info("web:[{}]", web);
            boolean s = webService.save(web);
            logService.Log(user.getUserName(), "添加网址:" + web.getWebName());
            return s ? ResponseVO.ok("添加成功") : ResponseVO.error("添加失败");

        }

    }

    /**
     * 上传网站图片
     *
     * @param file
     * @return
     */
    @PostMapping("/up")
    @ResponseBody
    public ResponseVO up(MultipartFile file, HttpSession session) {
        User user = (User) session.getAttribute(UserSessionName.USER);
        if (user == null) {

        }
        HashMap u = new HashMap();
        if (file.isEmpty()) {
            u.put("url", "");
            return ResponseVO.ok(u);
        }
        String url = null;
        try {
            url = webService.upPic(file, webPicUrl);
        } catch (IOException e) {
            log.error("上传图片出错");
            e.printStackTrace();
        }
        u.put("url", url);
        logService.Log(user.getUserName(), "上传图片");
        return ResponseVO.ok(u);

    }

    /**
     * 返回网址集合
     *
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public ResponseVO list() {
        QueryWrapper<Web> webQueryWra = new QueryWrapper<>();
        webQueryWra.eq("del", DeleteStatusEnum.NOT_DELETE.getCode());
        List<Web> list = webService.list(webQueryWra);
        return ResponseVO.ok(list);
    }

    /**
     * 删除，更新删除位
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    @ResponseBody
    public ResponseVO delete(Integer id, HttpSession session) {
        User user = (User) session.getAttribute(UserSessionName.USER);
        if (user == null) {
            return ResponseVO.error("请登录");
        }
        log.info("id::::{}", id);
        Web byId = webService.getById(id);
        byId.setDel(DeleteStatusEnum.DELETE.getCode());
        boolean b = webService.updateById(byId);
        // 删图片
        deleteWebPic();
        logService.Log(user.getUserName(), "删除网址: " + byId.getWebName());
        return b ? ResponseVO.ok("删除成功") : ResponseVO.error("删除失败");
    }

    // 删除本地图片
    private void deleteWebPic() {
        QueryWrapper<Web> wrapper = new QueryWrapper<>();
        wrapper.eq("del", DeleteStatusEnum.DELETE.getCode());
        wrapper.like("web_icon", "web");
        List<Web> list = webService.list(wrapper);
        List<String> img = new ArrayList<>();
        for (Web web : list) {
            img.add(web.getWebIcon().replace("/web/", ""));
        }
        for (String s : img) {
            FileUtil.del(webPicUrl + s);
        }
    }

    /**
     * 获取通过id
     *
     * @param id
     * @return
     */
    @PostMapping("/get")
    @ResponseBody
    public ResponseVO get(Integer id) {
        Web byId = webService.getById(id);
        return ResponseVO.ok(byId);
    }

}
